package builder 
{
	import app.AppModel;
	import app.AppSettings;
	import app.FurnitureClass;
	import app.FurnitureType;
	import app.textures.*;
	import drawing.FurniturePaletteProvider;
	import flash.display.Stage;
	import flash.net.URLLoader;
	import furnitures.FurnitureFactory;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import furnitures.FurnitureModel;
	import resources.Images;
	import tasks.BaseTask;
	import tasks.LoadMainXml;
	import utils.ErrorsCollector;
	
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class AppBuilderXML implements IAppBuilder
	{
		private var _model:AppModel;
		private var _parent:Stage;
		private var _task:LoadMainXml;
		
		public function AppBuilderXML(model:AppModel,  parent:Stage) 
		{
			_model = model;
			_parent = parent;
		}
		
		/* INTERFACE builder.IAppBuilder */
		
		public function start():void 
		{
			_model.inited = false;
			_model.roomHeight = 2700 * AppSettings.SCALE_FACTOR;
			_model.roomLength = 3000 * AppSettings.SCALE_FACTOR;
			_model.roomWidth = 3000 * AppSettings.SCALE_FACTOR;
			
			trace("_model.roomHeight: " + _model.roomHeight);
			
			// init palette
			_model.paletteProvider = new FurniturePaletteProvider();
			
			_model.facadeTextures = new Vector.<TextureInfoGroupe>();
			_model.tabletopTextures = new Vector.<TextureInfoGroupe>();
			
			// read flash vars
			var paramObj:Object = _parent.loaderInfo.parameters;
			var xmlPath:String = AppSettings.XML_FILE_NAME;
			var xmlKey:String = AppSettings.XML_KEY;
			
			if (paramObj[xmlKey] != undefined)
			{
				xmlPath = paramObj[xmlKey];
			}
			
			_task = new LoadMainXml(xmlPath, _model);
			_task.addEventListener(Event.CHANGE, handleTaskChange);
			_task.run();
		}
		
		private function handleTaskChange(e:Event):void 
		{
			_task.removeEventListener(Event.CHANGE, handleTaskChange);
			
			if (_task.ready)
			{
				_model.inited = true;
			}else
			{
				handleError("Can't build app, task not ready");
			}
		}
		
		private function handleError(err:String):void
		{
			ErrorsCollector.collectError("AppBuilderXML: " + err);
		}
		
		public function destroy():void 
		{
			_model = null;
			_parent = null;
			_task.destroy();
			_task = null;
		}
		
	}

}